package com.dingwen.treasure.slow.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dingwen.treasure.base.pojo.vo.PageVo;
import com.dingwen.treasure.base.pojo.vo.Result;
import com.dingwen.treasure.base.pojo.vo.ResultGenerator;
import com.dingwen.treasure.model.dto.PageDto;
import com.dingwen.treasure.model.entity.mybatisplus.SysUser;
import com.dingwen.treasure.mybatisplus.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 　优化Api
 * 　@author dingwen
 * 　@date 2022/8/5
 */
@Api(tags = "优化API")
@RestController
@Slf4j
@RequestMapping("optimize")
@Validated
public class OptimizeController {

    @Resource
    private SysUserService userService;


    /**
     * 适用于自增id
     * 数据总条数：4301000 </br>
     * <p>自带查询分页性能：</p>
     * <ul>
     *     <li>第 1 页 10 条关闭count查询优化耗时：4秒</li>
     *     <li>第 100,00 页 100 条关闭count查询优化耗时：5秒</li>
     *     <li>第 100,000 页 100 条关闭count查询优化耗时：5秒</li>
     *
     *     <li>第 1 页 10 条打开count查询优化耗时：4秒</li>
     *     <li>第 100,00 页 100 条打开count查询优化耗时：4秒</li>
     *     <li>第 100,000 页 100 条打开count查询优化耗时：4秒</li>
     * </ul>
     *
     * <p>优化后性能：</p>
     * <ul>
     *     <li>第 1 页 10 条耗时：30～80毫秒</li>
     *     <li>第 100,00 页 100 条耗时：30～80毫秒</li>
     *     <li>第 100,000 页 100 条耗时：30～80秒</li>
     * </ul>
     *
     * 再进行统计总记录条数时会遇到瓶颈，正确的处理方式应该是杜绝深分页，不会有用户往下翻到地100页
     * 一般选择50页即可
     *
     * @param pageDto 页面dto
     * @return {@link Result}<{@link PageVo}<{@link SysUser}>>
     */
    @PostMapping("/deep-page")
    @ApiOperation("深分页查询优化")
    public Result<PageVo<SysUser>> deepPage(@RequestBody PageDto pageDto) {
        Integer current = pageDto.getCurrent();
        Integer pageSize = pageDto.getPageSize();
        Page<SysUser> page = new Page<>(current, pageSize);
        // 可以选择关闭count查询优化，解决一对多时分页查询总计记录条数不正确问题
        page.setOptimizeCountSql(Boolean.TRUE);
        //return ResultUtil.genResult(userService.page(page));
        return ResultGenerator.genSuccessResult(userService.optimizeSelectPage(current,pageSize));
    }
}
